package com.taotao.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taotao.po.User;
import com.taotao.service.UserService;
import com.taotao.vo.AjaxResult;
import com.taotao.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("list")
    public ModelAndView list(UserVO userVO,ModelAndView mv) {
        Page<User> queryPage = Page.of(userVO.getPageNum(), userVO.getNumPerPage());
        LambdaQueryWrapper<User> queryWapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(userVO.getName())) {
            queryWapper.like(User::getName, userVO.getName());
        }
        Page<User> pageResult = userService.page(queryPage,queryWapper);
        mv.addObject("pageResult",pageResult);
        mv.setViewName("userList");
        return mv;
    }

    @RequestMapping("goAdd")
    public ModelAndView goAdd(ModelAndView mv) {
        mv.setViewName("userAdd");
        return mv;
    }

    @RequestMapping("add")
    @ResponseBody
    public AjaxResult add(User user) {
        user.setCreated(DateUtil.date());
        boolean saveRs = this.userService.save(user);
        if (saveRs) {
            return AjaxResult.ok();
        }
        return AjaxResult.fail();
    }

    @RequestMapping("batchDelete")
    @ResponseBody
    public AjaxResult batchDelete(String ids) {
        if (StrUtil.isBlank(ids)) {
            return AjaxResult.fail();
        }
        Arrays.stream(ids.split(",")).forEach(id -> {
            this.userService.removeById(Integer.valueOf(id));
        });
        return AjaxResult.okNoClose();
    }

    @RequestMapping("goUpdate")
    public ModelAndView goUpdate(Integer id, ModelAndView mv) {
        User user = this.userService.getById(id);
        mv.addObject("user", user);
        mv.setViewName("userUpdate");
        return mv;
    }

    @RequestMapping("update")
    @ResponseBody
    public AjaxResult update(User user) {
        boolean updateResult = this.userService.saveOrUpdate(user);
        if (updateResult) {
            return AjaxResult.ok();
        }
        return AjaxResult.fail();
    }


}
